import { useState, useEffect, useMemo, useLayoutEffect } from "react";
import { View, Text } from "@tarojs/components";
import Taro from "@tarojs/taro";
import Empty from "../component/empty";
import { getBrowserController, getStorage } from "@/pages/components/utils";
import LgRefreshPage from "@/pages/components/refreshPage";
import LgSearch from "@/pages/components/searchInput";
import LgSelepicker from "@/pages/components/selePick";
import { connect, useDispatch, useSelector } from "react-redux";
import { HttpGet, HttpPut, HttpDelete, HttpPost } from "@/network/servers";
import Util from "@/utils/index";
import _ from "lodash";
import { FloatingBubble, SwipeAction } from "antd-mobile";
import { AddOutline } from "antd-mobile-icons";
import Utils from "@/utils/index";
import Card from "../component/card";
import proxy from "@/network/proxy";
import "./index.scss";

var wx = require("weixin-js-sdk");

const browserController = getBrowserController();

const { recentDateStr, getQueryVariable } = Util;
const storage = getStorage();

export default function App() {
  const { userInfo, lg_ic, noticeAddr } = useSelector(
    (state: any) => state.commonData
  );

  const dispatch = useDispatch();

  const [noticeList, setNoticeList] = useState([]);
  const [allCount, setAllCount] = useState(0); //总数
  const [currentIndex, setCurrentIndex] = useState(1);
  const [pullCount, setPullCount] = useState(1);
  const [totalPage, setTotalPage] = useState(0);
  const [loadVisible, setLoadVisible] = useState(true);

  const [keyword, setKeyword] = useState("");
  const [isSearch, setIsSearch] = useState(false);

  const selectList = useMemo(() => {
    //不同身份下拉的选项不同
    // if (userInfo.UserType == 2 || userInfo.UserType == 3) {
    return [
      { key: "all", name: "全部" },
      { key: "noDeal", name: "待处理" },
      { key: "alreadyDeal", name: "已处理" },
    ];
    // } else {
    //   return [
    //     // { key: 'publish', name: '我发布的' },
    //     { key: 'receive', name: '我收到的' },
    //   ]
    // }
  }, [userInfo]);

  const [currentType, setCurrentType] = useState(selectList[0].key);

  const toSendPage = () => {
    if (!noticeAddr) {
      return;
    }
    let openUrl =
      noticeAddr +
      `/mobile/announcement/index.html?lg_tk=${Utils.getNowToken()}&lg_ic=${lg_ic}`;
    if (Utils.getSystemInfo() === "weapp") {
      openUrl = proxy.transmitUrlToVisit(
        noticeAddr +
          `/mobile/announcement/index.html?lg_tk=${Utils.getNowToken()}&lg_ic=${lg_ic}&env=weapp&schoolId=${
            userInfo.SchoolID
          }`
      );
    }
    window.open(openUrl, "_self");
  };

  const publishNotice = useMemo(() => {
    if (userInfo.UserType == 0 || userInfo.UserType == 1) {
      return (
        <FloatingBubble
          style={{
            "--initial-position-bottom": "59px",
            "--initial-position-right": "24px",
            "--background": "#3698fc",
            "--size": "44px",
          }}
          onClick={toSendPage}
        >
          <AddOutline fontSize={30} />
        </FloatingBubble>
      );
    } else {
      return <></>;
    }
  }, [userInfo]);

  const computeSwipe = (item) => {
    //计算滑块的操作项
    if (item.readStatus == 0) {
      return [
        {
          key: "shield",
          text: "设为已读",
          color: "#009cff",
          onClick: () => handleRead(item),
        },
        {
          key: "del",
          text: "删除",
          color: "#e75d58",
          fontSize: "15px",
          onClick: () => handleDel(item),
        },
      ];
    } else {
      return [
        {
          key: "del",
          text: "删除",
          color: "#e75d58",
          onClick: () => handleDel(item),
        },
      ];
    }
  };

  // 搜索变化
  const searchHandle = _.debounce(
    (value) => {
      setKeyword(value.trim());
    },
    500,
    { trailing: true }
  );

  const getToken = () => {
    if (getQueryVariable("env") === "weapp") {
      return getQueryVariable("lg_tk");
    } else {
      return storage.get("token") || getQueryVariable("lg_tk");
    }
  };

  const jumpWeapp = (appId, path) => {
    try {
      browserController.navigateToMiniProgramForWebview(wx, {
        appId, //必传 跳转小程序唯一标识
        path, //必传 跳转后初始页面路径
        extraData: {},
        envVersion: "release", //必传 跳转小程序的版本
      });
    } catch (err) {
      Taro.showToast({ title: err, icon: "none" });
    }
  };
  // 点击事件
  const toDetail = (item) => {
    if (item.noticeId) {
      const taskId=item.taskReleaseId || ""
      Taro.navigateTo({
        url:
          "/pages/messageApp/noticeDetail/index?id=" +
          item.noticeId +
          "&from=home" +
          "&taskReleaseId=" +
          taskId,
      });
    } else {
      if (Utils.getSystemInfo() === "h5") {
        //app环境
        if (item.pcLinkType == 1 && item.appLink) {
          Taro.getSysWeb({ sysId: item.sysId }, "web", function (res) {
            let url =
              res +
              item.appLink
                .replace("[token]", getToken())
                .replace(
                  "[IdentityCode]",
                  storage.get("lg_ic") || Utils.getQueryVariable("lg_ic")
                )
                .replace(
                  "[identityCode]",
                  storage.get("lg_ic") || Utils.getQueryVariable("lg_ic")
                );
            window.open(url, "_self");
          });
        } else if (item.pcLinkType == 3 && item.appLink) {
          window.open(item.appLink, "_self");
        } else if (item.pcLinkType == 4) {
          // if (item.templateId === '20002') {
          //   showMeSchedule(item)
          // } else if (item.templateId === '26003') {
          //   showMeAssignment(item)
          // } else if (item.templateId === '00027') {
          //   showMeActive(item)
          // }
          dispatch({
            type: "SHOW_TOAST",
            data: "block",
          });
        } else {
          // Toast.show({
          //   content: '请前往电脑端查看详情',
          //   position: 'bottom',
          // })
          dispatch({
            type: "SHOW_TOAST",
            data: "block",
          });
        }
      } else {
        if (item.pcLinkType == 1 && item.appletsLink) {
          if (item.appletsLink.includes("wxLogin")) {
            //存在小程序跳转非H5嵌入
            let paramsArr = item.appletsLink.split("#");
            let appid = paramsArr[0];
            let path = paramsArr[1];

            for (let i = 2; i < paramsArr.length; i++) {
              //若传入的链接包含多个# 则将第二个#连接的参数作为path
              path += "#" + paramsArr[i];
            }
            jumpWeapp(appid, path);
          } else {
            Taro.getSysWeb({ sysId: item.sysId }, "web", function (data) {
              let url =
                data +
                item.appletsLink
                  .replace("[token]", Utils.getNowToken())
                  .replace("[identityCode]", lg_ic)
                  .replace("[IdentityCode]", lg_ic);
              window.open(proxy.transmitUrlToVisit(url), "_self");
            });
          }
        } else if (item.pcLinkType == 3 && item.appletsLink) {
          window.open(item.appletsLink, "_self");
        } else if (item.pcLinkType == 4) {
          // if (item.templateId === '20002') {
          //   showMeSchedule(item)
          // } else if (item.templateId === '26003') {
          //   showMeAssignment(item)
          // } else if (item.templateId === '00027') {
          //   showMeActive(item)
          // }
        } else {
          // Toast.show({
          //   content: '请前往电脑端查看详情',
          //   position: 'bottom',
          // })
          dispatch({
            type: "SHOW_TOAST",
            data: "block",
          });
        }
      }
    }
  };

  const getShowThisMsg = (item) => {
    //获取当前待办在此环境是否展示
    if (Utils.getSystemInfo() === "weapp") {
      //小程序环境
      switch (String(item.receiverType)) {
        case "0":
        case "3":
        case "5":
        case "6":
          return true;
        default:
          return false;
      }
    } else {
      switch (String(item.receiverType)) {
        case "0":
        case "2":
        case "4":
        case "6":
          return true;
        default:
          return false;
      }
    }
  };

  const handleType = (item) => {
    setCurrentType(item.key);
  };

  // 获取通知信息
  const getNoticeList = (n = pullCount) => {
    let { SchoolID, UserID, UserType } = userInfo;

    let classNoticeArr = [],
      noticeTotal = 0,
      status = "",
      readStatus = "" as any;

    switch (currentType) {
      case "all":
        break;
      case "noDeal":
        status = "0";
        readStatus = 0;
        break;
      case "alreadyDeal":
        status = "3";
        readStatus = 1;
        break;
      default:
        break;
    }
    if (UserType == 2 || UserType == 3) {
      HttpGet({
        url: "/api/todo/list/getPageList?noticeType=1",
        data: {
          pageIndex: 1,
          pageSize: 9999,
          keyWord: keyword,
          userId: userInfo.UserID,
          userType: userInfo.UserType,
          schoolId: userInfo.SchoolID,
          noticeType: 1,
          status,
        },
        load: true,
      }).then((result) => {
        let todoNum = Number(result.total);
        let oldTodoInfo = [];
        noticeTotal += todoNum;
        oldTodoInfo = result.data;
        let newTodoInfo = [];
        if (oldTodoInfo.length > 0) {
          oldTodoInfo.forEach(function (item) {
            if (getShowThisMsg(item)) {
              newTodoInfo.push(item);
            }
          });
        }
        classNoticeArr = newTodoInfo;

        HttpGet({
          url: noticeAddr + `/api/notice/list/receiver/page/1/9999`,
          data: {
            userId: userInfo.UserID,
            schoolId: userInfo.SchoolID,
            keyword,
            noticeNature: 3,
            readStatus,
          },
          load: true,
        }).then((data) => {
          if (data.code === "200") {
            let isInit = true;

            if (isInit) {
              classNoticeArr = classNoticeArr.concat(data.data.notices);
              noticeTotal += Number(data.data.total);
            }

            classNoticeArr.forEach(function (item: any, index) {
              item.key = item?.msgId || item?.noticeId || index;
              item.dueTime = Date.parse(
                item.msgPushTime || item.taskReleaseTime || item.releaseTime
              );
            });

            classNoticeArr.sort(function (a: any, b: any) {
              return b.dueTime - a.dueTime;
            });

            // console.log(classNoticeArr);
            setNoticeList(classNoticeArr);
            setLoadVisible(false);
          }
        });
      });
    } else {
      HttpGet({
        url: noticeAddr + `/api/notice/list/receiver/page/1/${10 * n}`,
        data: {
          userId: UserID,
          schoolId: userInfo.SchoolID,
          keyword,
          noticeNature: 3,
          readStatus,
        },
        load: true,
      }).then((result) => {
        const noticeArr = result.data.notices;
        noticeArr &&
          noticeArr.forEach((item) => {
            item.isChecked = false;
          });
        setAllCount(result.data.total);
        setTotalPage(Math.ceil(result.data.total / 10));
        setNoticeList(noticeArr);
        setLoadVisible(false);
      });
    }
  };

  const handleRead = (item) => {
    HttpPut({
      url: noticeAddr + `/api/notice/receiver/batch/read`,
      data: {
        userId: userInfo.UserID,
        noticeIds: [item.noticeId],
        taskReleaseIds: item.taskReleaseId ? [item.taskReleaseId] : [],
      },
    }).then(() => {
      getNoticeList();
      window.getNewRemindCount &&
        typeof window.getNewRemindCount &&
        window.getNewRemindCount();
      Taro.showToast({
        title: "已读成功",
        duration: 2000,
        mask: true,
      });
    });
  };

  const handleDel = (item) => {
    Taro.showModal({
      title: "提示",
      content: "是否删除所选通知",
      success: function (res) {
        if (res.confirm) {
          HttpDelete({
            url: noticeAddr + "/api/notice/receiver/batch/del",
            data: {
              userId: userInfo.UserID,
              noticeIds: [item.noticeId],
              taskReleaseIds: item.taskReleaseId ? [item.taskReleaseId] : [],
            },
          }).then((result) => {
            getNoticeList();
            Taro.showToast({
              title: "删除成功",
              duration: 2000,
              mask: true,
            });
          });
        } else if (res.cancel) {
          console.log("用户点击取消");
        }
      },
    });
  };

  // 无限刷新
  const onPull = () => {
    if (totalPage > pullCount) {
      setTimeout(() => {
        Taro.showLoading();
        Taro.hideLoading();
      }, 2000);
      setPullCount(pullCount + 1);
      getNoticeList(pullCount + 1);
    } else {
      Taro.showToast({
        title: "到底啦",
        icon: "none",
      });
    }
  };
  // 下拉刷新
  const onDown = () => {
    getNoticeList();
    setTimeout(() => {
      Taro.showToast({
        title: "刷新成功",
      });
    }, 500);
  };

  useEffect(() => {
    getNoticeList();
  }, [currentIndex, keyword, currentType]);

  useLayoutEffect(() => {
    window.getNoticeList = getNoticeList; //全局方法
  }, [pullCount, currentIndex, keyword, currentType]);

  return (
    <View className="notice_container">
      33333333333
      {/* <View className="notice_option">
        <LgSelepicker
          type="B"
          id="sele3"
          className="left"
          dataList={selectList}
          changeSele={handleType}
          attr="name"
        />
        {isSearch ? (
          <View className="my_ipt  animate__animated animate__slideInRight animate__faster">
            <LgSearch
              value={keyword}
              onConfirm={(value: string) => setKeyword(value.trim())}
              placeholder="请输入..."
              onInput={searchHandle}
            />
          </View>
        ) : (
          <View
            className="my_search_icon"
            onClick={() => setIsSearch(true)}
          ></View>
        )}
      </View>
      <LgRefreshPage
        className="index"
        onPull={onPull}
        onDown={onDown}
        downText={["下拉刷新", "释放刷新"]}
        pullText={["上拉加载更多", "释放加载更多"]}
      >
        {noticeList && noticeList.length > 0 ? (
          noticeList.map((item: any, index) => {
            if (item.noticeId) {
              return (
                <SwipeAction rightActions={computeSwipe(item)}>
                  <View
                    key={item.taskReleaseId || item.noticeId}
                    className="notice_box"
                  >
                    <View>
                      <Card
                        type="B"
                        key={index}
                        title={item.title}
                        content={item.content}
                        noticeType={item.noticeType}
                        time={recentDateStr(item.startTime)}
                        publisher={item.userName}
                        isRead={item.readStatus == 1 ? true : false}
                        toLink={() => {
                          toDetail(item);
                        }}
                      />
                    </View>
                  </View>
                </SwipeAction>
              );
            } else {
              return (
                <Card
                  type="A"
                  key={index}
                  title={item.msgSourceName}
                  publisher={item.userName}
                  content={item.msgPushContent}
                  startTime={recentDateStr(item.msgPushTime)}
                  endTime={item.msgPushExpire}
                  status={item.status}
                  toDetail={() => {
                    toDetail(item);
                  }}
                />
              );
            }
          })
        ) : loadVisible ? (
          ""
        ) : (
          <Empty />
        )}
      </LgRefreshPage>
      {publishNotice} */}
    </View>
  );
}
